package com.github.ghsea.sso.client.security.cas;

import com.github.ghsea.sso.client.config.ShiroConfig;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author guhai
 * <p>
 * 重写LogoutFilter，为重定向的url
 */
@Component(value = "logoutFilter")
public class LogoutFilterExt extends LogoutFilter {

    @Autowired
    private ShiroConfig shiroConfig;

    @Override
    protected void issueRedirect(ServletRequest request, ServletResponse response, String redirectUrl) throws Exception {
        Optional<String> originUrlOp = WebUtil.getOriginUrl(request);
        if (originUrlOp.isPresent()) {
            redirectUrl = redirectUrl + "?" + WebUtil.ORIGIN_URL_PARAMETER + "=" + originUrlOp.get();
        }

        if (WebUtil.isTokenSession(request)) {
            Map ret = new HashMap<>();
            ret.put("code", 200);
            ret.put("status", "success");
            ret.put("message", "退出登录成功");
            ret.put("data", redirectUrl);
            WebUtil.writeJson(ret, response);
            return;
        } else {
            super.issueRedirect(request, response, redirectUrl);
        }
    }

    @Autowired
    public void setRedirectUrl() {
        super.setRedirectUrl(shiroConfig.getCasServerUrl() + "/logout");
    }

}
